function [mode, objf, objgrd, user] = myfun_mean(mode, n, w, objgrd, nstate,user)

    %%%%%%%%%%%%%%%%%%%%%%%
    % UNPACK USER STRUCTURE
    %%%%%%%%%%%%%%%%%%%%%%%

[SS,x1,x2,~,~,~,~,~,~,~,~,~,~]=user_unpack(user);

    %%%%%%%%%%%%%%%%%%%%%%%
    % PREDICT SHAT AND RESIDUAL
    %%%%%%%%%%%%%%%%%%%%%%%

[shat,S,~,~]=predict_demand_share(x1,x2,w,user);
u=SS-shat;
    
    %%%%%%%%%%%%%%%%%%%%%%%
    % COMPUTE OBJECTIVE FUNCTION
    %%%%%%%%%%%%%%%%%%%%%%%
    
check_f=u'*u;
check_fderiv=2*u';

if isreal(check_f)==0,
    error('non-real objf');
end;
    
    %%%%%%%%%%%%%%%%%%%%%%%
    % COMPUTE DERIVATIVE
    %%%%%%%%%%%%%%%%%%%%%%%

d_u_d_beta = -S;

    %%%%%%%%%%%%%%%%%%%%%%%
    % PREPARE OUTPUT
    %%%%%%%%%%%%%%%%%%%%%%%

objf=check_f;
objgrd = check_fderiv*d_u_d_beta;

    %
